I have to get data from a Postgres DB for my project. The API is supplying a list of country codes in the form of a string like "US, IN, PK". The Table Countries has the country ID for each country code. The table user has the User ID for each user. Now the table User_Country contains the mapping i.e. if a user has permission for a certain country signified by the has_approval flag which is a Boolean. The query has to return the information of all the users who have the has_approval flag true for all the given countries I have written the following code which runs three different queries for the same. However, I think we can write a single query using Outer join.
let countryList = countryIds.split(","); // countryIds = "US,IN,PK"
let countryIdList = [];
let countryId = "";
for(let i = 0; i < countryList.length; i++){
countryId = await Country.findOne({
attributes: ['id'],
where: {
ctrn_cd : countryList[i]
},
raw: true
});
countryIdList.push(countryId.id);
}
let users = await Users.findAll({
attributes: ['id'],
raw: true
})
let UserIds = [];
for(let i = 0; i < users.length; i ++){
let countryCount = await UserCountry.count({
where: {
ctrn_id : countryIdList,
user_id: users[i].id,
has_approval: true
},
raw: true
});
if(countryCount == countryIdList.length) UserIds.push(users[i].id);
}
let layoutapprovers = await User.findAll({
attributes: ['id', 'guid', ['role_id','roleId'], 'name', ['email','emailId']],
where:{
id: UserIds
},
raw: true
});
return layoutapprovers;```